'use strict';

const BaseService = require('./base');

class RoleService extends BaseService {
  get _model() {
    return 'UserAndRole';
  }

  async findOne({ id, rid }) {
    const { ctx } = this;
    const where = this.formatWhere({ exact: { id, rid } });
    const include = [
      {
        model: ctx.model.User,
        attributes: {
          exclude: [ 'password' ],
        },
      },
      {
        model: ctx.model.Role,
      },
    ];
    return this._findOne({ where, include });
  }

  async create({ uid, rid }) {
    return this._create({
      uid, rid,
    });
  }

  async update({ rid, id }) {
    const body = { rid };
    const where = { id };
    return this._update({ body, where });
  }

  async destory(id) {
    const where = { id };
    return this._destory({ where });
  }

  async findList({ rid, prop, sort, pageIndex, pageSize, createdAt }) {
    const { ctx } = this;
    const where = this.formatWhere({ range: { createdAt } });
    const order = this.formatOrder(prop, sort);
    const roleWhere = this.formatWhere({ exact: { id: rid } });
    const include = [
      {
        model: ctx.model.User,
        attributes: [ 'userName', 'nickName' ],
      },
      {
        model: ctx.model.Role,
        attributes: [ 'name' ],
        where: roleWhere,
      },
    ];
    return this._findList({ pageIndex, pageSize, where, include, order });
  }

  async findAll() {
    return this._findAll();
  }
}

module.exports = RoleService;
